package com.cjl.demo.juc;

/**
 * <p>Copyright: All Rights Reserved</p>
 * <p>Description: DCL(Double Check Locking 双端检锁) 机制不一定线程安全,
 * 原因是有指令重排的存在,加入volatile可以禁止指令重排</p>
 *
 * @ uthor chenjinliang
 * @ date: 2020/2/16
 */
public class SingletonDemo {
    private static volatile SingletonDemo instance = null;

    private SingletonDemo() {
        System.out.println(Thread.currentThread().getName() + "\t 构造方法");
    }

    /**
     * 双重检测机制
     *
     * @return
     */
    public static SingletonDemo getInstance() {
        if (instance == null) {
            synchronized (SingletonDemo.class) {
                if (instance == null) {
                    instance = new SingletonDemo();
                }
            }
        }
        return instance;
    }

    public static void main(String[] args) {
        for (int i = 1; i <= 10; i++) {
            new Thread(() -> {
                SingletonDemo.getInstance();
            }, String.valueOf(i)).start();
        }
    }

}
